import tips from '../../lib/tips';
import request from '../../utils/request'
Page({
  data: {
    // 设置菊花初始状态
    loading: false,
    addressesList: [],
    defaultId: 0,
    tipsData: {
      title: ''
    }
  },
  goEdit(event) {
    const id = event.target.dataset.addressId;
    wx.navigateTo({
      url: `../address-edit/address-edit?id=${id}`
    });
  },
  delete(event) {
    const id = event.target.dataset.addressId;
    let addressList = this.data.addressesList;
      resource.successToast(() => {
        const defaultData = addressList.find(itm => itm.items.isDefault === true);
        if (+defaultData.id === +id && addressList.length > 0) {
          addressList = addressList.filter(itm => +itm.id !== +id);
        }
        this.setData({
          defaultId: defaultData.address_id,
          addressesList: addressList.filter(itm => +itm.id !== +id)
        });
      });
  },
  setDefault(event) {
    const checkedId = + event.currentTarget.dataset.valueId || +event.detail.value;
    let setFlag = false;
    wx.request({
      url: 'http://localhost:8000/address/updateDefault',
      data:{
        id : checkedId,
        flag : 1
      },
      method: "GET"
    })
      setFlag = true;
      this.data.addressesList.forEach((itm) => {
        if (itm) {
          itm.items.isDefault = +itm.id === checkedId;
          itm.items.iconType = itm.items.isDefault ? 'success' : 'circle';
          itm.items.iconColor = itm.items.iconType === 'success' ? '#FF2D4B' : '';
        }
      });
      this.setData({ addressesList: this.data.addressesList });
      wx.showToast({
        title: '设置成功',
        icon: 'success'
      })
  },
  onShow(){
    this.getAddress();
  },
  onLoad() {
    tips.toast(this.data.tipsData);
    const tipsData = {
      title: 'sku不足zz',
      duration: 2000,
      isHidden: false
    };
    this.setData({
      tipsData
    });
    setTimeout(() => {
      tipsData.isHidden = true;
      this.setData({
        tipsData
      });
    }, 3000);
    this.getAddress();      
  },
  async getAddress(){
    let adddressData = await request("/address/get");
    if (adddressData.data) {
      adddressData.data.forEach((item) => {
        item.overlayConfirm = false;
        item.items = {
          id: item.id,
          is_default: item.isDefault,
          isgroup: true,
          labelText: '设置为默认',
          iconType: item.isDefault ? 'success' : 'circle'
        };
        item.items.iconColor = item.items.iconType === 'success' ? '#FF2D4B' : '';
      });
      this.setData({
        addressesList: adddressData.data,
        loading: false
      });
    } else {
      this.setData({
        addressesList: [],
        loading: false
      });
    }
  }
});
